package org.liveboardgames.agricola.control.delegates
{
    import flash.utils.setTimeout;
    
    import org.liveboardgames.agricola.vo.common.IResourceContainer;
    import org.liveboardgames.common.dictionary.collections.HashCollection;
    
    import mx.rpc.IResponder;
    
    public class MoveResourceDelegate
    {
        private var _responder:IResponder;
        
        private var _service:Object;
        
        public function MoveResourceDelegate(responder:IResponder)
        {
            // this.service = ServiceLocator.getInstance().getRemoteObject( "helloWorldService" );
            this._responder = responder;
        }
        
        public function moveResources(origin:IResourceContainer, destination:IResourceContainer, resources:HashCollection):void
        {
            setTimeout(moveResourcesService, 0, origin, destination, resources);
        }
        
        private function moveResourcesService(origin:IResourceContainer, destination:IResourceContainer, resources:HashCollection):void
        {
            if (destination.resources == null)
            {
                destination.resources = new HashCollection();
            }
            
            for each (var resourceType:String in resources.getKeys())
            {
                var movedQuantity:int = resources.getValue(resourceType) as int;
                
                // Remove the resources from the origin
                var originalQuantity:int = origin.resources.getValue(resourceType) as int;
                var newQuantity:int = Math.max(0, originalQuantity - movedQuantity);
                origin.resources.put(resourceType, newQuantity);
                
                // Add the resources to the destination
                var destinationQuantity:int = destination.resources.getValue(resourceType) as int;
                var newDestinationQuantity:int = Math.max(0, destinationQuantity + movedQuantity);
                destination.resources.put(resourceType, newDestinationQuantity);
            }
        }
    }
}